<template>
	<view>
		<view>
			<image src="/static/login/header.png" mode="widthFix" class="response"></image>
			<view class="content">
				<view class="input">
					<input type="text" v-model="name" placeholder="请输入账号" />
				</view>
				<view class="input">
					<input type="password" v-model="password" placeholder="请输入密码" />
				</view>

				<button class="cu-btn block bg-blue margin-tb-sm lg" @click="clickLogin">登 录</button>
			</view>
		</view>
	</view>
</template>

<script>
	import ui from '../../util/ui.js'
	import apiPatrol from '../../util/apis/api-patrol.js'
	import md5 from 'js-md5'


	const LOGIN_INFO = "LOGIN_INFO";
	export default {
		data() {
			return {
				name: "",
				password: ""
			}
		},
		onLoad() {
			// 取缓存
			let loginInfo = uni.getStorageSync(LOGIN_INFO);
			if (loginInfo) {
				this.name = loginInfo.username;
				this.password = loginInfo.password;
				// 自动登录
				this.apiLogin(true);
			}

		},
		methods: {

			// ——————————————————————————————点击方法————————————————————————————————
			/**
			 * 点击登录时的事件
			 */
			clickLogin: function() {
				if (this.name.trim().length == 0 || this.password.trim().length == 0) {
					ui.showErrorDialog('用户名或密码不能为空')
					return
				}
				this.apiLogin(false)
			},


			// ——————————————————————————————api方法————————————————————————————————
			/**
			 * @param {自动登录} autoLogin
			 * api登录的方法
			 */
			apiLogin: function(autoLogin) {
				ui.showLoading()
				let formData = {
					login_username: this.name,
					login_password: md5(this.password)
				}
				apiPatrol.login(formData)
					.then(res => {
						// 将auth存储在本地
						uni.setStorageSync('Authorization', res.Authorization)
						// 获取用户信息
						if (!autoLogin) {
							// 存储用户名、密码
							uni.setStorageSync(LOGIN_INFO, {
								username: this.name,
								password: this.password
							})
						}
						// 跳转到首页
						uni.redirectTo({
							url: '../index/index'
						})

					})
					.finally(() => {
						ui.hideLoading()
					})
			}
		}
	}
</script>

<style>
	page {
		height: 100vh;
		background-color: white;
	}

	.content {
		padding: 20px 16px;
		border-top-left-radius: 25px;
		border-top-right-radius: 25px;
		position: relative;
		top: -25px;
		background-color: white;
	}


	.input {
		margin-bottom: 20px;
	}

	.input input {
		padding: 10px;
		border-bottom: 1px solid #CCCCCC;
		height: auto;
	}
</style>
